using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using SqlsugarService.Infrastructure.DbContext;

namespace SqlsugarService.Infrastructure.Services
{
    /// <summary>
    /// 数据库初始化服务
    /// 提供手动初始化数据库表的功能
    /// </summary>
    public class DatabaseInitializationService
    {
        private readonly SqlSugarDbContext _dbContext;
        private readonly IConfiguration _configuration;
        private readonly ILogger<DatabaseInitializationService> _logger;

        public DatabaseInitializationService(
            SqlSugarDbContext dbContext,
            IConfiguration configuration,
            ILogger<DatabaseInitializationService> logger)
        {
            _dbContext = dbContext;
            _configuration = configuration;
            _logger = logger;
        }

        /// <summary>
        /// 手动初始化所有表
        /// </summary>
        /// <param name="forceRecreate">是否强制重新创建表</param>
        /// <returns></returns>
        public async Task<bool> InitializeTablesAsync(bool forceRecreate = false)
        {
            try
            {
                _logger.LogInformation("开始手动初始化数据库表...");

                // 直接调用现有DbContext的初始化方法
                await Task.Run(() =>
                {
                    // 模拟InitializeTables方法的逻辑
                    var entityTypes = new[]
                    {
                        typeof(SqlsugarService.Domain.Users),
                        typeof(SqlsugarService.Domain.BOM.BomInfo),
                        typeof(SqlsugarService.Domain.BOM.BomItem),
                        typeof(SqlsugarService.Domain.Craftsmanship.ProcessRouteEntity),
                        typeof(SqlsugarService.Domain.Craftsmanship.ProcessRouteStep),
                        typeof(SqlsugarService.Domain.Craftsmanship.ProcessStep),
                        typeof(SqlsugarService.Domain.Craftsmanship.ProcessStepProduct),
                        typeof(SqlsugarService.Domain.InventoryChange.Salesorder),
                        typeof(SqlsugarService.Domain.InventoryChange.SalesOutboundDetailEntity),
                        typeof(SqlsugarService.Domain.InventoryChange.SalesOutboundEntity),
                        typeof(SqlsugarService.Domain.Materials.MaterialCategory),
                        typeof(SqlsugarService.Domain.Materials.MaterialEntity),
                        typeof(SqlsugarService.Domain.Materials.ProcessStepMaterial),
                        typeof(SqlsugarService.Domain.Materials.ProductEntity),
                        typeof(SqlsugarService.Domain.Plan.ProductionOrder),
                        typeof(SqlsugarService.Domain.Plan.ProductionPlan),
                        typeof(SqlsugarService.Domain.Plan.WorkOrderTaskEntity),
                        typeof(SqlsugarService.Domain.QualityInspection.InspectionItemEntity),
                        typeof(SqlsugarService.Domain.QualityInspection.QualityInspectionPlanEntity),
                        typeof(SqlsugarService.Domain.QualityInspection.QualityPlanInspectionItemLink),
                        typeof(SqlsugarService.Domain.QualityInspection.WorkReportInspectionEntity),
                        typeof(SqlsugarService.Domain.Station.EquipmentEntity),
                        typeof(SqlsugarService.Domain.Station.StationEntity),
                        typeof(SqlsugarService.Domain.Station.ToolCategoryEntity),
                        typeof(SqlsugarService.Domain.Station.ToolEntity),
                        typeof(SqlsugarService.Domain.Team.TeamEntity),
                        typeof(SqlsugarService.Domain.Team.TeamMemberEntity),
                        typeof(SqlsugarService.Domain.Warehouse.InventoryOrderEntity),
                        typeof(SqlsugarService.Domain.Warehouse.TransferOrderEntity),
                        typeof(SqlsugarService.Domain.Warehouse.WarehouseAreaEntity),
                        typeof(SqlsugarService.Domain.Warehouse.WarehouseEntity),
                        typeof(SqlsugarService.Domain.Warehouse.WarehouseLocationEntity),

                    };

                    int createdCount = 0;
                    int existingCount = 0;

                    foreach (var entityType in entityTypes)
                    {
                        try
                        {
                            var tableName = _dbContext.Db.EntityMaintenance.GetTableName(entityType);

                            if (forceRecreate)
                            {
                                // 强制重建
                                _dbContext.Db.CodeFirst.InitTables(entityType);
                                _logger.LogInformation($"表 {tableName} ({entityType.Name}) 已重新创建");
                                createdCount++;
                            }
                            else
                            {
                                // 仅在表不存在时创建
                                if (!_dbContext.Db.DbMaintenance.IsAnyTable(tableName))
                                {
                                    _dbContext.Db.CodeFirst.InitTables(entityType);
                                    _logger.LogInformation($"表 {tableName} ({entityType.Name}) 不存在，已创建");
                                    createdCount++;
                                }
                                else
                                {
                                    _logger.LogDebug($"表 {tableName} ({entityType.Name}) 已存在，跳过创建");
                                    existingCount++;
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            _logger.LogError(ex, $"表 {entityType.Name} 处理失败: {ex.Message}");
                        }
                    }

                    _logger.LogInformation($"表初始化统计 - 创建: {createdCount}, 已存在: {existingCount}");
                });

                _logger.LogInformation("数据库表初始化完成");
                return true;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "数据库表初始化失败");
                return false;
            }
        }

        /// <summary>
        /// 检查数据库连接
        /// </summary>
        /// <returns></returns>
        public async Task<bool> CheckDatabaseConnectionAsync()
        {
            try
            {
                await _dbContext.Db.Ado.GetDataTableAsync("SELECT 1");
                _logger.LogInformation("数据库连接正常");
                return true;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "数据库连接失败");
                return false;
            }
        }

        /// <summary>
        /// 获取数据库中所有表的信息
        /// </summary>
        /// <returns></returns>
        public async Task<List<string>> GetAllTablesAsync()
        {
            try
            {
                var tables = _dbContext.Db.DbMaintenance.GetTableInfoList();
                return tables.Select(t => t.Name).ToList();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取表信息失败");
                return new List<string>();
            }
        }
    }
}